package com.juyu.miliao.common.netease;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.SocketConfig;
import org.apache.http.impl.NoConnectionReuseStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.*;

/**
 * 网易云信工具类
 * @author wbf
 */
public class NetEaseCloudUserService {
	
	private static final CloseableHttpClient httpClient ;
	private static final String from = "999";
	private static final String officialAssistant ="12890000";
	private static final String createUrl = "https://api.netease.im/nimserver/user/create.action";
	private static final String updateUrl = "https://api.netease.im/nimserver/user/update.action";
	private static final String system_message = "https://api.netease.im/nimserver/msg/sendAttachMsg.action";
	private static final String update_userInfo = "https://api.netease.im/nimserver/user/updateUinfo.action";
	private static final String get_userInfo = "https://api.netease.im/nimserver/user/getUinfos.action";
	private static final String sendMsg = "https://api.netease.im/nimserver/msg/sendMsg.action";
	private static final String recall_sendMsg = "https://api.netease.im/nimserver/msg/recall.action";
	private static final String send_batch_attach_msg = "https://api.netease.im/nimserver/msg/sendBatchAttachMsg.action";
	private static final String text_check = "https://as.dun.163yun.com/v3/text/check";
	private static final String unblockUserUrl = "https://api.netease.im/nimserver/user/unblock.action";
	private static final String deleteRoom = "https://roomserver-dev.netease.im/v1/api/rooms/%s";

	/** 云盾反垃圾*/
	/** 产品密钥ID，产品标识 */
	private final static String SECRETID = "f10b4a14faac4cc83de5e13f9013c363";
	/** 产品私有密钥，服务端生成签名信息使用，请严格保管，避免泄露 */
	private final static String SECRETKEY = "3037eeee6d795c16bb2780e3b873e357";
	/** 业务ID，易盾根据产品业务特点分配 */
	private final static String BUSINESSID = "0b05761d1e990664f99542151d224f5d";

	static {
	    //池化链接管理器
		PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
		cm.setMaxTotal(500);             //连接池的最大连接数
		cm.setDefaultMaxPerRoute(200);   //每个路由的最大连接数
        //默认请求配置
		RequestConfig requestConfig = RequestConfig
				.custom()
				.setConnectionRequestTimeout(1000) //从连接池获取连接的等待超时时间
				.setConnectTimeout(2000)            //设置连接超时时间 2s
				.setSocketTimeout(2000)             //设置等待数据超时时间 2s
				.build();
		httpClient = HttpClients.custom()
				.setConnectionManager(cm) //池化链接管理器
				.setDefaultRequestConfig(requestConfig) //默认请求配置
				.setConnectionReuseStrategy(NoConnectionReuseStrategy.INSTANCE)//连接重用策略 是否能keepAlive
                .setConnectionManagerShared(true) //开启连接池共享模式
                .setRetryHandler(new DefaultHttpRequestRetryHandler(0,false))//重试次数 默认3次 此处禁用
				.build();
	}

	public static int deleteRoom(String roomId) throws IOException{
		String deleteRoomUrl = String.format(deleteRoom,roomId);
		HttpDelete httpDelete = new HttpDelete(deleteRoomUrl);
		DecorateHttpHeader.getDecorateHttpHeaderToHttpDelete(httpDelete);
		// 执行请求
		try(CloseableHttpResponse response = httpClient.execute(httpDelete)){
			// 返回执行结果,code
			return response.getStatusLine().getStatusCode();
		}
	}

	/**
	 * 创建网易云通信ID
	 * @param accid 网易云通信ID APP内唯一
	 * @param token 网易云通信ID可以指定登录token值
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String createNetEaseId(String accid , String token) throws ClientProtocolException, IOException{
		HttpPost httpPost = new HttpPost(createUrl);
		DecorateHttpHeader.getDecorateHttpHeader(httpPost);
		// 设置请求的参数
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("accid", accid));
		nvps.add(new BasicNameValuePair("token", token));
		httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
		// 执行请求
		try(CloseableHttpResponse response = httpClient.execute(httpPost);){
			// 返回执行结果
			String temp = EntityUtils.toString(response.getEntity(), "utf-8");
			return temp;
		}
	}
	/**
	 * 更新网易云通信ID
	 * @param accid 网易云通信ID APP内唯一
	 * @param token 网易云通信ID可以指定登录token值
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String updateNetEaseId(String accid , String token) throws ClientProtocolException, IOException{
		HttpPost httpPost = new HttpPost(updateUrl);
		DecorateHttpHeader.getDecorateHttpHeader(httpPost);
		// 设置请求的参数
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("accid", accid));
		nvps.add(new BasicNameValuePair("token", token));
		httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
		// 执行请求
		try(CloseableHttpResponse  response = httpClient.execute(httpPost);){
			// 返回执行结果
			String temp = EntityUtils.toString(response.getEntity(), "utf-8");
			return temp;
		}
	}
	
	/**
	 * 发送点对点系统通知
	 */
	public static String getSystemMessage(String attach , Long userId) throws IOException{
		HttpPost httpPost = new HttpPost(system_message);
		DecorateHttpHeader.getDecorateHttpHeader(httpPost);
		// 设置请求的参数
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("from", from));
		nvps.add(new BasicNameValuePair("msgtype", "0"));
		nvps.add(new BasicNameValuePair("to", userId+""));
		nvps.add(new BasicNameValuePair("attach", attach));
		httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
		// 执行请求
		try(CloseableHttpResponse  response = httpClient.execute(httpPost);){
			// 返回执行结果
			String temp = EntityUtils.toString(response.getEntity(), "utf-8");
			return temp;
		}
	}
	/**
	 * 更新用户基本信息(用户昵称,头像)
	 * @param name
	 * @param accid
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String updateUserInfo(Long accid,String name,String icon) throws ClientProtocolException, IOException{
		HttpPost httpPost = new HttpPost(update_userInfo);
		DecorateHttpHeader.getDecorateHttpHeader(httpPost);
		// 设置请求的参数
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("accid", accid+""));
		if(name!= null && !name.equals("")&& !name.equals("null"))
			nvps.add(new BasicNameValuePair("name", name));
		if(icon!= null && !icon.equals("")&& !icon.equals("null"))
			nvps.add(new BasicNameValuePair("icon", icon));
		httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
		// 执行请求
		try(CloseableHttpResponse  response = httpClient.execute(httpPost)){
			// 返回执行结果
			String temp = EntityUtils.toString(response.getEntity(), "utf-8");
			return temp;
		}
	}
	
	
	/**
	 * 发送点对点普通消息
	 */
	public static String getSendMsg(long userId, long hostUserId, int type, String body, String ext,String pushcontent) throws IOException {
		HttpPost httpPost = new HttpPost(sendMsg);
		DecorateHttpHeader.getDecorateHttpHeader(httpPost);
		// 设置请求的参数
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("from", hostUserId+"")); //发送者accid
		nvps.add(new BasicNameValuePair("ope", "0")); //0：点对点个人消息
		nvps.add(new BasicNameValuePair("to", userId+"")); //ope==0是表示accid即用户id
		nvps.add(new BasicNameValuePair("type", type+"")); //0 表示文本消息,1 表示图片，100 表示自定义，
		nvps.add(new BasicNameValuePair("body", body+"")); //对应消息,为一个JSON串
		nvps.add(new BasicNameValuePair("ext", ext+"")); //开发者扩展字段
		nvps.add(new BasicNameValuePair("useYidun","0"));//不使用易盾反垃圾而是使用通用反垃圾
		if(type==100)
			nvps.add(new BasicNameValuePair("pushcontent", pushcontent)); //ios推送内容
		JSONObject json = new JSONObject();
		json.put("sendersync", "false");
		json.put("persistent", "false");
		nvps.add(new BasicNameValuePair("option",json.toString()));
		httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
		// 执行请求
		try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
			// 返回执行结果
			String temp = EntityUtils.toString(response.getEntity(), "utf-8");
			return temp;
		}
	}
	/**
	 * 注册专用
	 * 发送点对点普通消息
	 */
	public static String getSendMsgByRegister(long userId, long hostUserId, int type, String body, String ext,String pushcontent) throws IOException {
		HttpPost httpPost = new HttpPost(sendMsg);
		DecorateHttpHeader.getDecorateHttpHeader(httpPost);
		// 设置请求的参数
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("from", hostUserId+"")); //发送者accid
		nvps.add(new BasicNameValuePair("ope", "0")); //0：点对点个人消息
		nvps.add(new BasicNameValuePair("to", userId+"")); //ope==0是表示accid即用户id
		nvps.add(new BasicNameValuePair("type", type+"")); //0 表示文本消息,1 表示图片，100 表示自定义，
		nvps.add(new BasicNameValuePair("body", body+"")); //对应消息,为一个JSON串
		nvps.add(new BasicNameValuePair("ext", ext+"")); //开发者扩展字段
		nvps.add(new BasicNameValuePair("useYidun","0"));//不使用易盾反垃圾而是使用通用反垃圾
		if(type==100)
			nvps.add(new BasicNameValuePair("pushcontent", pushcontent)); //ios推送内容
		JSONObject json = new JSONObject();
		nvps.add(new BasicNameValuePair("option",json.toString()));
		httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
		// 执行请求
		try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
			// 返回执行结果
			String temp = EntityUtils.toString(response.getEntity(), "utf-8");
			return temp;
		}
	}

	/**
	 * 撤回点对点普通消息
	 * @param deleteMsgid 	要撤回消息的msgid
	 * @param timetag 要撤回消息的创建时间
	 * @param type 7:表示点对点消息撤回，8:表示群消息撤回，其它为参数错误
	 * @param fromUserId 发消息的accid
	 * @param toUserId 如果点对点消息，为接收消息的accid,如果群消息，为对应群的tid
	 * @return
	 * @throws IOException
	 */
	public static String recallSendMsg(String deleteMsgid,int type ,long fromUserId, long toUserId) throws IOException {
		HttpPost httpPost = new HttpPost(recall_sendMsg);
		DecorateHttpHeader.getDecorateHttpHeader(httpPost);
		// 设置请求的参数
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("deleteMsgid", deleteMsgid));
//		nvps.add(new BasicNameValuePair("timetag",timetag));
		nvps.add(new BasicNameValuePair("type", type+""));
		nvps.add(new BasicNameValuePair("from", fromUserId+""));
		nvps.add(new BasicNameValuePair("to", toUserId+""));
		nvps.add(new BasicNameValuePair("ignoreTime", "1"));
		httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
		// 执行请求
		try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
			// 返回执行结果
			return EntityUtils.toString(response.getEntity(), "utf-8");
		}
	}


	/**
	 * 获取用户名片
	 * @param accid
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String getUserInfo(JSONArray jsonArray) throws ClientProtocolException, IOException{
		HttpPost httpPost = new HttpPost(get_userInfo);
		DecorateHttpHeader.getDecorateHttpHeader(httpPost);
		// 设置请求的参数
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("accids", jsonArray.toString()));
		httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
		// 执行请求
		try(CloseableHttpResponse response = httpClient.execute(httpPost)){
			// 返回执行结果
			String temp = EntityUtils.toString(response.getEntity(), "utf-8");
			return temp;
		}
	}



	/**
	 * 批量发送点对点自定义系统通知
	 * 每次最大限500人
	 * 此接口受频率控制，一个应用一分钟最多调用120次，超过会返回416状态码，并且被屏蔽一段时间
	 * @param bodyJSON 发送消息内容
	 * @param idsJSON 接收id JSON数组
	 * @return 云信返回结果
	 * @throws IOException
	 */
	public static String sendBatchAttachMsg(String bodyJSON,String idsJSON) throws IOException{
		HttpPost httpPost = new HttpPost(send_batch_attach_msg);
		DecorateHttpHeader.getDecorateHttpHeader(httpPost);
		// 设置请求的参数
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		//发送者accid，用户帐号，最大32字符，APP内唯一
		nvps.add(new BasicNameValuePair("fromAccid", from));
		//["aaa","bbb"]（JSONArray对应的accid，如果解析出错，会报414错误），最大限500人
		nvps.add(new BasicNameValuePair("toAccids", idsJSON));
		//自定义通知内容，第三方组装的字符串，建议是JSON串，最大长度4096字符
		nvps.add(new BasicNameValuePair("attach", bodyJSON));
		//1表示只发在线，2表示会存离线，其他会报414错误。默认会存离线
		nvps.add(new BasicNameValuePair("save", 1+""));
		JSONObject json = new JSONObject();
		json.put("badge", "false"); //该消息是否需要计入到未读计数中，默认true;
		json.put("route", "false"); //该消息是否需要抄送第三方；默认true (需要app开通消息抄送功能)
		nvps.add(new BasicNameValuePair("option",json.toString()));
		httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
		// 执行请求
		try(CloseableHttpResponse  response = httpClient.execute(httpPost)){
			// 返回执行结果
			return EntityUtils.toString(response.getEntity(), "utf-8");
		}
	}


	/**
	 * 云信-云盾反垃圾
	 * @param text 要检测的文本内容
	 * @return
	 * @throws IOException
	 */
	public static String getYunTextCheck(String text) throws  IOException{
		HttpPost httpPost = new HttpPost(text_check);

		// 1.设置公共参数
		Map<String, String> params = new HashMap<String, String>();
		params.put("secretId", SECRETID);
		params.put("businessId", BUSINESSID);
		params.put("version", "v3.1");
		params.put("timestamp", String.valueOf(System.currentTimeMillis()));
		params.put("nonce", String.valueOf(new Random().nextInt()));
		// 2.设置私有参数
		params.put("dataId", "ebfcad1c-dba1-490c-b4de-e784c2691768");
		params.put("content", text);
		// 3.生成签名信息
		String signature = SignatureUtils.genSignature(SECRETKEY, params);
		params.put("signature", signature);

		List<NameValuePair> list = new ArrayList<NameValuePair>();
		for (String key : params.keySet()) {
			list.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
		}
		httpPost.setEntity(new UrlEncodedFormEntity(list, "utf-8"));
		// 执行请求
		try(CloseableHttpResponse  response = httpClient.execute(httpPost)){
			// 返回执行结果
			return EntityUtils.toString(response.getEntity(), "utf-8");
		}
	}

	/**
	 * 解封云信账号
	 * @param userId
	 * @return
	 * @throws IOException
	 */
	public static String unBlockUserById(long userId) throws IOException{
		HttpPost httpPost = new HttpPost(unblockUserUrl);
		DecorateHttpHeader.getDecorateHttpHeader(httpPost);
		// 设置请求的参数
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("accid", userId+""));
		httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
		// 执行请求
		try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
			// 返回执行结果
			return EntityUtils.toString(response.getEntity(), "utf-8");
		}
	}
}
